<template>
  <div class="location-picker" :class="{ 'show': isVisible }">
    <div class="location-picker-overlay" @click="handleClose"></div>
    <div class="location-picker-content" @click.stop>
      <div class="location-picker-header">
        <h3>选择地点</h3>
        <button class="location-picker-close" @click="handleClose">×</button>
      </div>
      
      <div class="location-picker-search">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索地点..."
          class="location-search-input"
          @input="handleSearch"
          @keydown.enter="handleEnterKey"
        />
      </div>
      
      <div class="location-picker-tabs">
        <div 
          class="location-tab" 
          :class="{ 'active': activeTab === 'recent' }"
          @click="activeTab = 'recent'"
        >
          最近地点
        </div>
        <div 
          class="location-tab" 
          :class="{ 'active': activeTab === 'favorite' }"
          @click="activeTab = 'favorite'"
        >
          收藏地点
        </div>
        <div 
          class="location-tab" 
          :class="{ 'active': activeTab === 'popular' }"
          @click="activeTab = 'popular'"
        >
          热门地点
        </div>
      </div>
      
      <div class="location-picker-body">
        <div v-if="searchQuery && searchResults.length > 0" class="location-results">
          <div 
            v-for="location in searchResults" 
            :key="location.id"
            class="location-item"
            @click="handleSelectLocation(location)"
          >
            <i class="location-icon">📍</i>
            <div class="location-info">
              <div class="location-name">{{ location.name }}</div>
              <div class="location-address">{{ location.address }}</div>
            </div>
            <button 
              class="favorite-btn" 
              :class="{ 'favorited': location.isFavorite }"
              @click="toggleFavorite(location, $event)"
            >
              {{ location.isFavorite ? '❤️' : '🤍' }}
            </button>
          </div>
        </div>
        
        <div v-else-if="searchQuery && searchResults.length === 0" class="no-results">
          未找到相关地点
        </div>
        
        <div v-else-if="activeTab === 'recent'" class="location-results">
          <div v-if="recentLocations.length > 0">
            <div 
              v-for="location in recentLocations" 
              :key="location.id"
              class="location-item"
              @click="handleSelectLocation(location)"
            >
              <i class="location-icon">📍</i>
              <div class="location-info">
                <div class="location-name">{{ location.name }}</div>
                <div class="location-address">{{ location.address }}</div>
              </div>
              <button 
                class="favorite-btn" 
                :class="{ 'favorited': location.isFavorite }"
                @click="toggleFavorite(location, $event)"
              >
                {{ location.isFavorite ? '❤️' : '🤍' }}
              </button>
            </div>
          </div>
          <div v-else class="no-results">
            暂无最近使用的地点
          </div>
        </div>
        
        <div v-else-if="activeTab === 'favorite'" class="location-results">
          <div v-if="favoriteLocations.length > 0">
            <div 
              v-for="location in favoriteLocations" 
              :key="location.id"
              class="location-item"
              @click="handleSelectLocation(location)"
            >
              <i class="location-icon">📍</i>
              <div class="location-info">
                <div class="location-name">{{ location.name }}</div>
                <div class="location-address">{{ location.address }}</div>
              </div>
              <button 
                class="favorite-btn favorited"
                @click="toggleFavorite(location, $event)"
              >
                ❤️
              </button>
            </div>
          </div>
          <div v-else class="no-results">
            暂无收藏的地点
          </div>
        </div>
        <div v-else-if="activeTab === 'popular'" class="location-results">
          <div 
            v-for="location in popularLocations" 
            :key="location.id"
            class="location-item"
            @click="handleSelectLocation(location)"
          >
            <i class="location-icon">📍</i>
            <div class="location-info">
              <div class="location-name">{{ location.name }}</div>
              <div class="location-address">{{ location.address }}</div>
            </div>
            <button 
              class="favorite-btn" 
              :class="{ 'favorited': location.isFavorite }"
              @click="toggleFavorite(location, $event)"
            >
              {{ location.isFavorite ? '❤️' : '🤍' }}
            </button>
          </div>
        </div>
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading-overlay">
          <div class="loading-spinner"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LocationPicker',
  props: {
    isVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchQuery: '',
      activeTab: 'recent',
      recentLocations: [],
      popularLocations: [
        { id: 1, name: '北京天安门', address: '北京市东城区西长安街', lat: 39.908692, lng: 116.397477, isFavorite: false },
        { id: 2, name: '上海外滩', address: '上海市黄浦区中山东一路', lat: 31.240416, lng: 121.490317, isFavorite: false },
        { id: 3, name: '广州塔', address: '广州市海珠区阅江西路222号', lat: 23.109722, lng: 113.324520, isFavorite: false },
        { id: 4, name: '深圳世界之窗', address: '深圳市南山区深南大道9037号', lat: 22.531479, lng: 113.975377, isFavorite: false },
        { id: 5, name: '杭州西湖', address: '浙江省杭州市西湖区龙井路1号', lat: 30.242091, lng: 120.146284, isFavorite: false },
        { id: 6, name: '成都太古里', address: '成都市锦江区中纱帽街8号', lat: 30.631551, lng: 104.080742, isFavorite: false },
        { id: 7, name: '重庆解放碑', address: '重庆市渝中区邹容路100号', lat: 29.562844, lng: 106.582558, isFavorite: false },
        { id: 8, name: '武汉黄鹤楼', address: '湖北省武汉市武昌区蛇山西山坡特1号', lat: 30.545613, lng: 114.302942, isFavorite: false }
      ],
      favoriteLocations: [],
      isLoading: false,
      searchTimer: null,
      openedAt: 0
    }
  },
  computed: {
    searchResults() {
      if (!this.searchQuery) return []
      const query = this.searchQuery.toLowerCase()
      return this.popularLocations.filter(location => 
        location.name.toLowerCase().includes(query) || 
        location.address.toLowerCase().includes(query)
      )
    },
    displayLocations() {
      if (this.searchQuery) return this.searchResults
      if (this.activeTab === 'recent') return this.recentLocations
      if (this.activeTab === 'favorite') return this.favoriteLocations
      return this.popularLocations
    }
  },
  watch: {
    isVisible(newVal) {
      if (newVal) {
        this.loadUserData()
        this.openedAt = Date.now()
      } else {
        // 关闭时清除搜索
        this.searchQuery = ''
        if (this.searchTimer) {
          clearTimeout(this.searchTimer)
        }
      }
    }
  },
  mounted() {
    this.loadUserData()
  },
  methods: {
    loadUserData() {
      this.loadRecentLocations()
      this.loadFavoriteLocations()
    },
    loadRecentLocations() {
      try {
        const recent = localStorage.getItem('recentLocations')
        if (recent) {
          this.recentLocations = JSON.parse(recent)
        }
      } catch (error) {
        console.error('加载最近地点失败:', error)
      }
    },
    saveRecentLocations() {
      try {
        localStorage.setItem('recentLocations', JSON.stringify(this.recentLocations))
      } catch (error) {
        console.error('保存最近地点失败:', error)
      }
    },
    loadFavoriteLocations() {
      try {
        const favorite = localStorage.getItem('favoriteLocations')
        if (favorite) {
          this.favoriteLocations = JSON.parse(favorite)
          // 更新popularLocations中的收藏状态
          this.updateFavoriteStatus()
        }
      } catch (error) {
        console.error('加载收藏地点失败:', error)
      }
    },
    saveFavoriteLocations() {
      try {
        localStorage.setItem('favoriteLocations', JSON.stringify(this.favoriteLocations))
      } catch (error) {
        console.error('保存收藏地点失败:', error)
      }
    },
    updateFavoriteStatus() {
      // 更新热门地点的收藏状态
      this.popularLocations.forEach(location => {
        const isFav = this.favoriteLocations.some(fav => fav.id === location.id)
        location.isFavorite = isFav
      })
    },
    toggleFavorite(location, event) {
      // 阻止事件冒泡，避免触发选择
      if (event) {
        event.stopPropagation()
      }
      
      const existingIndex = this.favoriteLocations.findIndex(fav => fav.id === location.id)
      if (existingIndex !== -1) {
        // 移除收藏
        this.favoriteLocations.splice(existingIndex, 1)
        location.isFavorite = false
      } else {
        // 添加收藏
        this.favoriteLocations.unshift({ ...location, isFavorite: true })
        location.isFavorite = true
      }
      
      this.saveFavoriteLocations()
    },
    handleSearch() {
      // 防抖搜索，避免频繁更新
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      this.isLoading = true
      this.searchTimer = setTimeout(() => {
        // 搜索逻辑已在computed中处理
        this.isLoading = false
      }, 300)
    },
    handleEnterKey() {
      if (this.searchResults.length > 0) {
        this.handleSelectLocation(this.searchResults[0])
      }
    },
    handleSelectLocation(location) {
      // 添加选择动画效果
      const element = event.target
      if (element) {
        element.style.transform = 'scale(0.95)'
        setTimeout(() => {
          element.style.transform = 'scale(1)'
        }, 100)
      }
      
      // 添加到最近使用
      const existingIndex = this.recentLocations.findIndex(loc => loc.id === location.id)
      if (existingIndex !== -1) {
        // 移除已存在的，放在最前面
        this.recentLocations.splice(existingIndex, 1)
      }
      this.recentLocations.unshift({ ...location })
      
      // 限制最近地点数量
      if (this.recentLocations.length > 10) {
        this.recentLocations.pop()
      }
      
      this.saveRecentLocations()
      
      // 延迟触发选择事件，让动画效果显示
      setTimeout(() => {
        // 触发选择事件
        this.$emit('select', location)
        
        // 重置搜索和关闭选择器
        this.searchQuery = ''
        this.handleClose()
      }, 150)
    },
    handleClose() {
      // 避免打开瞬间由冒泡或误触导致立即关闭
      if (Date.now() - this.openedAt < 220) return
      const content = this.$el.querySelector('.location-picker-content')
      if (content) {
        const isDesktop = window.innerWidth >= 768
        if (isDesktop) {
          content.style.transition = 'transform 0.2s ease, opacity 0.2s ease'
          content.style.transform = 'translate(-50%, -40%)'
          content.style.opacity = '0'
        } else {
          content.style.transform = 'translateY(100%)'
        }
        setTimeout(() => { this.$emit('close') }, 220)
      } else {
        this.$emit('close')
      }
    }
  }
}
</script>

<style scoped>
.location-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: none;
}

.location-picker.show {
  display: block;
}

.location-picker-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.location-picker-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease-out;
  animation-fill-mode: both;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.location-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.location-picker-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.location-picker-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.location-picker-close:hover {
  background-color: #f5f5f5;
}

.location-picker-search {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.location-search-input {
  width: 100%;
  padding: 10px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.location-search-input:focus {
  border-color: #1677ff;
}

.location-picker-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.location-tab {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: color 0.2s;
}

.location-tab:hover {
  color: #1677ff;
}

.location-tab.active {
  color: #1677ff;
}

.location-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 30%;
  right: 30%;
  height: 2px;
  background-color: #1677ff;
}

.location-picker-body {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.location-results {
  padding: 0 16px;
}

.location-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.location-item:hover {
  background-color: #fafafa;
  transform: translateX(2px);
}

.location-item:last-child {
  border-bottom: none;
}

.favorite-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  opacity: 0.6;
  transition: all 0.2s;
  flex-shrink: 0;
  margin-left: auto;
}

.favorite-btn:hover {
  opacity: 1;
  transform: scale(1.2);
}

.favorite-btn.favorited {
  opacity: 1;
  animation: heartBeat 0.3s ease;
}

@keyframes heartBeat {
  0% { transform: scale(1); }
  50% { transform: scale(1.3); }
  100% { transform: scale(1); }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1677ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 优化移动端点击效果 */
@media (max-width: 768px) {
  .location-item:active {
    transform: scale(0.98);
    background-color: #f0f0f0;
  }
  
  .location-picker-content {
    animation: slideUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  }
}

/* 优化搜索框 */
.location-search-input {
  width: 100%;
  padding: 10px 16px 10px 40px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: all 0.2s;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23999' viewBox='0 0 16 16'%3E%3Cpath d='M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: 12px center;
}

.location-search-input:focus {
  border-color: #1677ff;
  box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}

/* 优化标签样式 */
.location-picker-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.location-tab {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  font-weight: 500;
}

.location-tab:hover {
  color: #1677ff;
  background-color: rgba(22, 119, 255, 0.05);
}

.location-tab.active {
  color: #1677ff;
  background-color: white;
  font-weight: 600;
}

.location-icon {
  font-size: 20px;
  margin-right: 12px;
  flex-shrink: 0;
}

.location-info {
  flex: 1;
}

.location-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.location-address {
  font-size: 13px;
  color: #999;
  line-height: 1.4;
}

.no-results {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 响应式设计 */
@media (min-width: 768px) {
  .location-picker-content {
    width: min(720px, 90vw);
    max-width: 720px;
    right: auto;
    left: 50%;
    top: 50%;
    bottom: auto;
    transform: translate(-50%, -50%);
    border-radius: 16px;
    margin-bottom: 0;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    animation: slideUpDesktop 0.25s ease-out;
  }
  
  @keyframes slideUpDesktop {
    from {
      opacity: 0;
      transform: translate(-50%, -40%);
    }
    to {
      opacity: 1;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
